﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using TestBat.IViewModels.Base;
using TestBat.ServiceLocator;

namespace TestBat.ViewModels.Base
{
    public class ViewModel : IViewModel
    {
        public IUnsavedChangesViewModel UnsavedChanges
        {
            get
            {
                if (unsavedChanges == null)
                    unsavedChanges = DefaultServiceLocator.Get<IUnsavedChangesViewModel>();
                return unsavedChanges;
            }
        }

        protected virtual void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected virtual void NotifyPropertiesChanged()
        {
            if (PropertyChanged != null)
            {
                // get properties
                PropertyInfo[] properties = this.GetType().GetProperties();
                foreach (var property in properties)
                    PropertyChanged(this, new PropertyChangedEventArgs(property.Name));
            }
        }

        protected virtual void NotifyPropertyChanged<TValue>(Expression<Func<TValue>> propertySelector)
        {
            if (PropertyChanged != null)
            {
                var memberExpression = propertySelector.Body as MemberExpression;
                if (memberExpression != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private IUnsavedChangesViewModel unsavedChanges;
    }
}
